#include<iostream>
#include<memory>
#include"Http.hpp"
#include"TcpServer.hpp"

void User(std::string proc)
{
    std::cout<<"Usage: "<<proc<<" localport"<<std::endl;
}

// std::string Handler(const std::string&request)
// {
//     std::cout<<"###################"<<std::endl;
//     std::cout<<request<<std::endl;
//     std::cout<<"###################"<<std::endl;

//     std::string resp="HTTP/1.1 200 OK\r\n\r\n";
//     resp+="<!DOCTYPE html>\r\n<html>\r\n<head>\r\n\
//     <title>Hello World</title>\r\n</head>\r\n<body>\r\n\
//     Hello World</body>\r\n</html>";
//     return resp;
// }
HttpResponse Login(HttpRequest& req)
{
    // 登录的时候，你需要什么？？username and passwd
    HttpResponse resp;
    LOG(Loglevel::DEBUG)<< "-----Login: " << req.Body();
    //重定向到首页
    resp.SetCode(302);
    resp.SetCookie("Set-Cookie", "k=1");
    resp.SetHeader("Location", "/");

    LOG(Loglevel::DEBUG)<< "-----Login: " << req.Body();

    return resp;
}
HttpResponse Register(HttpRequest& req)
{
    LOG(Loglevel::DEBUG)<< "-----Register" << req.Body();
}

HttpResponse Search(HttpRequest& req)
{
    LOG(Loglevel::DEBUG)<< "-----Search"<< req.Body();
}

int main(int args,char*argv[])
{   
    if(args!=2)
    {
        User(argv[0]);
        exit(0);
    }
    EnableConsoleLogStrategy();
    //HTTP协议
    std::unique_ptr<Http> http=std::make_unique<Http>();
    http->Register("/login", Login);
    http->Register("/register", Register);
    http->Register("/search", Search);
    //会话层
    uint16_t port=std::stoi(argv[1]);
    std::unique_ptr<TcpServer> tsock=std::make_unique<TcpServer>(port,
        [&http](std::string reqstr)->std::string{
            return http->HanderRequert(reqstr);
        }    
    );
    tsock->Run();
    return 0;
}